// pages/game/color_over.js

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    point: 0,
    record: 0,
    num: 0,
    isClick: false,
    isShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.updateFlag(this)
    console.log(options.level,options.score,options.desc)
    let defeat = (options.score * 100 / 32).toFixed(2)
    console.log(defeat)
    let unit = 0
    wx.getSystemInfo({
      success: function(res) {
        unit = parseFloat(res.screenWidth / 100)
      },
    })
    this.setData({
      level: options.level,
      score: options.score,
      desc: options.desc,
      defeat: defeat > 100 ? 100 : defeat,
      unit: unit,
      isAuth: app.isAuth
    })
  },
  return_act() {
    wx.redirectTo({
      url: '../game/color_index',
    })
  },
  return_index() {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  returnIndex () {
    wx.redirectTo({
      url: 'color_index',
    })
  },
  getPoint () {
    let that = this
    app.request(app.apiDomain + 'index.php?c=games&a=colors',{
      point: that.data.score
    },function (res) {
      let point = res.data.data.point
      let total = res.data.data.total
      let showGold = point > 0 ? true : false
      if (showGold) {
        const innerAudioContext = wx.createInnerAudioContext('qian_1')
        innerAudioContext.autoplay = true
        innerAudioContext.src = 'http://resource.160nurse.com/canvas/healthy/img/zou_lu/qian.mp3'
        innerAudioContext.onPlay(() => {
          console.log('开始播放')
        });
      } else {
        if (total < 20) {
          wx.showToast({
            title: '尚未达到金币领取条件,继续加油！',
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '今日领取金币数已达上限，可继续挑战',
            icon: 'none',
            duration: 2000
          })
        }
        
      }
      that.setData({
        point: point,
        showGold
      })
    }, 'POST')
  },
  getRecord () {
    let that = this
    app.request(app.apiDomain + 'index.php?c=games&a=ColorsRecord', {
      point: that.data.score
    }, function (res) {
      console.log(res)
      that.setData({
        record: res.data.data.point
      })
    }, 'POST')
  },
  gotoIndex () {
    wx.redirectTo({
      url: 'color_index',
    })
  },
  openAuth () {
    this.setData({
      isShow: true
    })
  },
  authSuccess(e) {
    let that = this
    console.log(app.isAuth)
    this.setData({
      isShow: false,
      isAuth: app.isAuth
    })
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) { //是否已授权用户信息
        } else {
          that.getPoint()
          that.getRecord()
        }
      }
    })
  },
  authFail(e) {
    this.setData({
      isShow: false,
      isAuth: app.isAuth
    })
  },
  click() {
    this.setData({
      isShow: false,
      isAuth: app.isAuth
    })
  },
  // getUserInfo: function () {
  //   var that = this
  //   if (app.getUserInfo(that)) {
  //     that.getAuth()
  //   }
  // },
  // open 分享和生成图片
  openInvite() {
    let that = this
    that.setData({
      openInvite: true
    })
  },
  closeInvite() {
    let that = this
    that.setData({
      openInvite: false,
      openSave: false
    })
  },
  genePic() {
    let that = this
    that.setData({
      openSave: true
    })
    this.geneHb()
  },
  getGoodsImgPath: function (url) {
    return new Promise((success, fail) => {
        wx.getImageInfo({
          src: url,
          success: res => {
            success(res.path);
          },
          fail: res => {
            fail(res);
          }
        })
    });
  },
  // 生成海报
  geneHb() {
    let that = this
    wx.showLoading({
      title: '正在准备海报',
      icon: 'none'
    })
    let ctx = wx.createCanvasContext('share_pic')
    let url = ''
    let url_text = ''
    if (that.data.score <= 8) {
      url = 'https://resource.160nurse.com/canvas/healthy/img/semang/1.png'
      url_text = 'https://resource.160nurse.com/canvas/healthy/img/semang/8.png'
    } else if (that.data.score <= 16) {
      url = 'https://resource.160nurse.com/canvas/healthy/img/semang/2.png'
      url_text = 'https://resource.160nurse.com/canvas/healthy/img/semang/6.png'
    } else if (that.data.score <= 24) {
      url = 'https://resource.160nurse.com/canvas/healthy/img/semang/3.png'
      url_text = 'https://resource.160nurse.com/canvas/healthy/img/semang/7.png'
    } else {
      url = 'https://resource.160nurse.com/canvas/healthy/img/semang/4.png'
      url_text = 'https://resource.160nurse.com/canvas/healthy/img/semang/5.png'
    }
    that.getGoodsImgPath(url).then((res) => {
      ctx.save()
      ctx.drawImage(res, 0, 0, 80 * that.data.unit, 132 * that.data.unit)
      ctx.restore()
      ctx.setFontSize(4.8 * that.data.unit)
      ctx.fillStyle = '#fff'
      ctx.fillText('健康160“辨色大挑战”', 16.46 * that.data.unit, 12.93 * that.data.unit)
      ctx.fillStyle = 'rgba(255,255,255,.7)'
      ctx.setFontSize(3.2 * that.data.unit)
      ctx.fillText('本次闯关记录：' + that.data.score + '关', 24.46 * that.data.unit, 17.93 * that.data.unit)
      ctx.fillStyle = '#3339D7'
      ctx.setFontSize(4.8 * that.data.unit)
      ctx.fillText('经鉴定，您是：', 5.86 * that.data.unit, 32.26 * that.data.unit)
      that.getGoodsImgPath(url_text).then((ress) => {
        ctx.save()
        ctx.drawImage(ress, 5.86 * that.data.unit, 37.26 * that.data.unit, 46.66 * that.data.unit, 8.53 * that.data.unit)
        ctx.restore()
        ctx.setFontSize(4.8 * that.data.unit)
        ctx.fillStyle = '#214F73'
        ctx.fillText('击败了全国', 5.86 * that.data.unit, 54 * that.data.unit)
        ctx.fillStyle = '#ED4441'
        ctx.fillText(that.data.defeat + '%', 5.86 * that.data.unit, 60 * that.data.unit)
        ctx.fillStyle = '#214F73'
        ctx.fillText('的用户', 23.5 * that.data.unit, 60 * that.data.unit)
        ctx.draw()
        wx.hideLoading()
      })
    })
    // ctx.drawImage(url_text, 5.86 * that.data.unit, 37.26 * that.data.unit, 46.66 * that.data.unit, 8.53 * that.data.unit)
  },
  saveImg () {
    let that = this
    if (that.data.isClick) {
      return false
    }
    wx.showToast({
      title: '保存中...',
      icon: 'none'
    })
    let shareImg = ''
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 80 * that.data.unit,
      height: 132 * that.data.unit,
      destWidth: 80 * that.data.unit * 2,
      destHeight: 132 * that.data.unit * 2,
      canvasId: 'share_pic',
      quality: 1,
      success(res) {
       shareImg = res.tempFilePath
        console.log(res.tempFilePath)
        wx.getSetting({
          success: function (res) {
            that.setData({
              isClick: true
            })
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: function (resp) {
                // let imgUrl = shareImg
                // console.log(imgUrl)
                // wx.downloadFile({
                //   url: imgUrl,
                //   success: function (res) {
                //     wx.hideLoading()
                //     // console.log(respon);
                    wx.saveImageToPhotosAlbum({
                      filePath: shareImg,
                      success: function (response) {
                        console.log(response)
                        that.setData({
                          isClick: false,
                          openInvite: false
                        })
                        wx.hideLoading()
                        wx.showToast({
                          title: '保存成功',
                          icon: 'success'
                        })
                      }
                    })
                //   }
                // })
              },
              fail: function () {
                wx.hideLoading()
                that.setData({
                  isClick: false
                })

              },
              complete: function (res) {
                // wx.hideLoading()
                console.log(res)
                if (res.errMsg.indexOf('authorize:fail') !== -1) {
                  wx.showToast({
                    title: '您未打开授权，请前往个人中心授权管理开启授权',
                    icon: 'none'
                  })
                }
                that.setData({
                  isClick: false
                })
              }
            })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.SystemInfo(this)
  },
  getAuth () {
    let that = this
    wx.getSetting({
      success: function (res) {
        if (!res.authSetting['scope.userInfo']) {
          that.setData({
            isAuth: false
          })
        } else {
          that.setData({
            isAuth: true
          })
          if (that.data.num == 1) {
            that.data.number ++
            that.getPoint()
            that.getRecord()
          }
        }
      }
    })
  },
  goRank () {
    wx.navigateTo({
      url: 'rank',
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.num++
    this.getAuth()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this
    let nickName = '';
    let userId = 0;
    let imgUrl = ''
    if (this.data.score <= 8) {
      imgUrl = app.resourceDomain + 'canvas/healthy/img/color/semang.png'
    } else if (this.data.score <= 16){
      imgUrl = app.resourceDomain + 'canvas/healthy/img/color/heshang.png'
    } else if (this.data.score <= 24) {
      imgUrl = app.resourceDomain + 'canvas/healthy/img//color/haose.png'
    } else {
      imgUrl = app.resourceDomain + 'canvas/healthy/img//color/most.jpg'
    }
    try {
      nickName = wx.getStorageSync('nickname');
      userId = wx.getStorageSync('user_id');
    } catch (e) { }

    return {
      path: "/pages/game/color_index?user_id=" + userId,
      title: '“辨色大挑战”，我闯过了' + that.data.score + '关，击败了全国' + that.data.defeat +'%的对手。',
      imageUrl: imgUrl
    }
  }
})